import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import {
  Button,
  Form,
  Input,
  InputNumber,
  Modal,
  Popconfirm,
  Result,
  Table,
  Tabs,
  TabsProps,
  Upload,
  UploadProps,
  message,
} from 'antd';
import { UploadChangeParam, UploadFile } from 'antd/es/upload';
import { useEffect, useState } from 'react';
import {
  getCommodity,
  getDrug,
  getMain,
  getMedicalServices,
  postAdd,
  postAddCommodity,
  postDrug,
  postMedicalServices,
  postPet,
  deleteCommodity,
  updateCommodity,
  deleteGG,
  updateMedicalServices,
  deleteMedicalService,
  deleteDrug,
  updateDrug
} from '../Register/service';
import { history } from '@umijs/max';

const Admin = () => {
  const [isModalOpen1, setIsModalOpen1] = useState(false);
  const [isModalOpen2, setIsModalOpen2] = useState(false);
  const [isModalOpen3, setIsModalOpen3] = useState(false);
  const [isModalOpen4, setIsModalOpen4] = useState(false);
  const [isModalOpen5, setIsModalOpen5] = useState(false);
  const [isModalOpen11, setIsModalOpen11] = useState(false);
  const [isModalOpen33, setIsModalOpen33] = useState(false);
  const [isModalOpen44, setIsModalOpen44] = useState(false);
  const [isModalOpen55, setIsModalOpen55] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const [loading, setLoading] = useState(false);
  const [avatar, setAvatar] = useState('');
  const [form] = Form.useForm();
  const [commodity, setCommdity] = useState([]);
  const [main,setMain] = useState([])
  const [drug,setDrug] = useState([])
  const [mediclList,setMedicaList] = useState([])
  const [refreshCount, setRefreshCount] = useState(0);
  const [row,setRow] = useState({})

  const fetchCommodity = async () => {
    const result = await getCommodity({
      pageNum:1
    });
    if (result.state === 200) {
      console.log(result);
      setCommdity(result?.data);
    }
  };
  const fetchMain = async () => {
    const result = await getMain()
    if(result.state === 200){
      setMain(result.data)
    }
  }
  const fetchMedicalServices = async () => {
    const result = await getMedicalServices()
    if(result.state === 200){
      console.log(result)
      setMedicaList(result.data)
    }
  }
  const fetchDrug = async () => {
    const result = await getDrug()
    if(result.state === 200){
      console.log(result)
      setDrug(result.data)
    }
  }
  useEffect(() => {
    fetchCommodity()
    fetchMain()
    fetchMedicalServices()
    fetchDrug()
  },[refreshCount])

  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.onload = () => {
      const Base64Data = reader.result;
      setAvatar(Base64Data);
    };
    reader.readAsDataURL(img);
  };

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You casdfsdfn only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps['onChange'] = (
    info: UploadChangeParam<UploadFile>,
  ) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      console.log(info);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );


  const columns = [
    {
      title: '商品名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
    },
    {
      title: '操作',
      dataIndex: 'address',
      key: 'address',
      render: (_, row) => {
        return (
          <span>
            <a href="#" onClick={() => {
              setIsModalOpen11(true)
              setRow(row)
              form.setFieldsValue({name:row?.name,price:row?.price,stock:row?.stock})
            }}>编辑</a>{' '}
            <Popconfirm
              title="确认删除吗"
              okText="确认"
              cancelText="取消"
              onConfirm={async() => {
                const result = await deleteCommodity({
                  cid:row?.cid
                })
                if(result.state === 200){
                  message.success('删除成功')
                  setRefreshCount(refreshCount + 1)
                }
              }}
            >
              <a href="#">删除</a>
            </Popconfirm>
          </span>
        );
      },
    },
  ];


  const columns2 = [
    {
      title: '图片',
      dataIndex: 'picture',
      key: 'picture',

    },
    {
      title: '地址',
      dataIndex: 'url',
      key: 'url',
      render:(_,row) => {
        return(
          <a onClick={() => {
            window.open('https://www.baidu.com')
          }}>{row?.url}</a>
        )
       
      }
    },
    {
      title: '操作',
      dataIndex: 'address',
      key: 'address',
      render: (_, row) => {
        return (
          <span>
            <Popconfirm
              title="确认删除吗"
              okText="确认"
              cancelText="取消"
            >
              <a href="#" onClick={async () => {
                const result = await deleteGG({

                })
              }}>删除</a>
            </Popconfirm>
          </span>
        );
      },
    },
  ];


  const columns3 = [
    {
      title: '名称',
      dataIndex: 'mtype',
      key: 'mtype',
    },
    {
      title: '库存',
      dataIndex: 'mstock',
      key: 'mstock',
    },
    {
      title: '操作',
      dataIndex: 'address',
      key: 'address',
      render: (_, row) => {
        return (
          <span>
            <a href="#" onClick={() => {
              setIsModalOpen33(true)
              setRow(row)
              form.setFieldsValue({mtype:row?.mtype,mstock:row?.mstock})
            }}>编辑</a>{' '}
            <Popconfirm
              title="确认删除吗"
              okText="确认"
              cancelText="取消"
              onConfirm={async () => {
                  const result = await deleteMedicalService({
                    mid:row?.mid
                  })
                  if(result.state === 200){
                    message.success('删除成功')
                    setRefreshCount(refreshCount + 1)
                  }
              }}
            >
              <a href="#" >删除</a>
            </Popconfirm>
          </span>
        );
      },
    },
  ];


  const columns4 = [
    {
      title: '名称',
      dataIndex: 'drugType',
      key: 'drugType',
    },
    {
      title: '库存',
      dataIndex: 'drugStock',
      key: 'drugStock',
    },
    {
      title: '操作',
      dataIndex: 'address',
      key: 'address',
      render: (_, row) => {
        return (
          <span>
            <a href="#" onClick={() => {
              setIsModalOpen44(true)
              setRow(row)
              form.setFieldsValue({
                drugType:row?.drugType,
                drugStock:row?.drugStock
              })
            }}>编辑</a>{' '}
            <Popconfirm
              title="确认删除吗"
              okText="确认"
              cancelText="取消"
              onConfirm={async () => {
                const result = await deleteDrug({
                  drugId:row?.drugId
                })
                if(result.state === 200){
                  message.success('删除成功')
                  setRefreshCount(refreshCount + 1)
                }
              }}
            >
              <a href="#">删除</a>
            </Popconfirm>
          </span>
        );
      },
    },
  ];


  const items: TabsProps['items'] = [
    {
      key: '1',
      label: `商品`,
      children: (
        <div>
          <Button
            onClick={() => {
              setIsModalOpen1(true);
            }}
          >
            添加商品
          </Button>
          <Table dataSource={commodity} columns={columns} />;
        </div>
      ),
    },
    {
      key: '2',
      label: `广告`,
      children: (
        <div>
          <Button
            onClick={() => {
              setIsModalOpen2(true);
            }}
          >
            添加广告
          </Button>
          <Table dataSource={main} columns={columns2} />;
        </div>
      ),
    },
    {
      key: '3',
      label: `医疗服务`,
      children: (
        <div>
          <Button
            onClick={() => {
              setIsModalOpen3(true);
            }}
          >
            添加医疗服务
          </Button>
          <Table dataSource={mediclList} columns={columns3} />;
        </div>
      ),
    },
    {
      key: '4',
      label: `医疗用品`,
      children: (
        <div>
          <Button
            onClick={() => {
              setIsModalOpen4(true);
              setRow(row)
            }}
          >
            添加医疗用品
          </Button>
          <Table dataSource={drug} columns={columns4} />;
        </div>
      ),
    },
    {
      key: '5',
      label: `宠物信息`,
      children: (
        <div>
          <Button
            onClick={() => {
              setIsModalOpen5(true);
            }}
          >
            发布宠物信息
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div>
      {
        JSON.parse(window.localStorage.getItem('info')).username === 'admin' ? 
        <div>
   <Tabs defaultActiveKey="1" items={items} />
      <Modal
        title="添加商品"
        open={isModalOpen1}
        onCancel={() => setIsModalOpen1(false)}
        onOk={async () => {
          const params = form.getFieldsValue();
          if (params) {
            const result = await postAddCommodity({
              ...params,
              picture: JSON.stringify(avatar),
            });
            if (result.state === 200) {
              message.success('添加成功');
              setIsModalOpen1(false);
              setRefreshCount(refreshCount + 1)
            }
          }
          form.submit();
        }}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          // onFinish={async(val) => {
          //   console.log(val)

          // }}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="商品名"
            name="name"
            rules={[{ required: true, message: '请输入商品名' }]}
          >
            <Input placeholder="请输入商品名" />
          </Form.Item>
          <Form.Item
            label="价格"
            name="price"
            rules={[{ required: true, message: '请输入价格' }]}
          >
            <InputNumber placeholder="请输入价格" />
          </Form.Item>
          <Form.Item
            label="库存"
            name="stock"
            rules={[{ required: true, message: '请输入库存' }]}
          >
            <InputNumber placeholder="请输入库存" />
          </Form.Item>
          <Form.Item label="图片" valuePropName="picture1">
            <Upload
              name="picture1"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="添加广告"
        open={isModalOpen2}
        onCancel={() => setIsModalOpen2(false)}
        onOk={async () => {
          const params = form.getFieldsValue();
          if (params) {
            const result = await postAdd({
              ...params,
              picture: JSON.stringify(avatar),
            });
            if (result.state === 200) {
              message.success('添加成功');
              setIsModalOpen2(false);
              setRefreshCount(refreshCount + 1)
            }
          }
          form.submit();
        }}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          // onFinish={async(val) => {
          //   console.log(val)

          // }}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="图片" valuePropName="picture1">
            <Upload
              name="picture1"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
          <Form.Item
            label="地址"
            name="url"
            rules={[{ required: true, message: '请输入地址' }]}
          >
            <Input placeholder="请输入地址" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="添加医疗服务"
        open={isModalOpen3}
        onCancel={() => setIsModalOpen3(false)}
        onOk={async () => {
          const params = form.getFieldsValue();
          if (params) {
            const result = await postMedicalServices({
              ...params,
            });
            if (result.state === 200) {
              message.success('添加成功');
              setIsModalOpen3(false);
              setRefreshCount(refreshCount + 1)
            }
          }
          form.submit();
        }}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          // onFinish={async(val) => {
          //   console.log(val)

          // }}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="名称"
            name="mtype"
            rules={[{ required: true, message: '请输入名称' }]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item
            label="库存"
            name="mstock"
            rules={[{ required: true, message: '请输入库存' }]}
          >
            <InputNumber placeholder="请输入库存" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="添加医疗用品"
        open={isModalOpen4}
        onCancel={() => setIsModalOpen4(false)}
        onOk={async () => {
          const params = form.getFieldsValue();
          if (params) {
            const result = await postDrug({
              ...params,
            });
            if (result.state === 200) {
              message.success('添加成功');
              setIsModalOpen4(false);
              setRefreshCount(refreshCount + 1)
            }
          }
          form.submit();
        }}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          // onFinish={async(val) => {
          //   console.log(val)

          // }}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="名称"
            name="drugType"
            rules={[{ required: true, message: '请输入名称' }]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item
            label="库存"
            name="drugStock"
            rules={[{ required: true, message: '请输入库存' }]}
          >
            <InputNumber placeholder="请输入库存" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="发布宠物信息"
        open={isModalOpen5}
        onCancel={() => setIsModalOpen5(false)}
        onOk={async () => {
          try {
            const params = form.getFieldsValue();
            if (params) {
              const result = await postPet({
                ...params,
                picture: JSON.stringify(avatar),
                // uid:32
              });
              console.log(result);
              if (result.state === 200) {
                message.success('添加成功');
                setIsModalOpen5(false);
                setRefreshCount(refreshCount + 1)
              }
            }
          } catch (error) {
            message.error('用户不存在');
          }
          form.submit();
        }}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          // onFinish={async(val) => {
          //   console.log(val)

          // }}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="图片" valuePropName="picture1">
            <Upload
              name="picture1"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
          <Form.Item label="用户名" name="username">
            <Input placeholder="请输入用户名" />
          </Form.Item>
        </Form>
      </Modal>






      <Modal
        title="编辑商品"
        open={isModalOpen11}
        onCancel={() => {
          setIsModalOpen11(false)
        }}
        onOk={async () => {
          const params = form.getFieldsValue();
          if (params) {
            const result = await updateCommodity({
              ...params,
              picture: JSON.stringify(avatar),
              cid:row?.cid
            });
            if (result.state === 200) {
              message.success('编辑成功');
              setIsModalOpen11(false);
            }
          }
          form.submit();
        }}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          // onFinish={async(val) => {
          //   console.log(val)

          // }}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="商品名"
            name="name"
            rules={[{ required: true, message: '请输入商品名' }]}
          >
            <Input placeholder="请输入商品名" />
          </Form.Item>
          <Form.Item
            label="价格"
            name="price"
            rules={[{ required: true, message: '请输入价格' }]}
          >
            <InputNumber placeholder="请输入价格" />
          </Form.Item>
          <Form.Item
            label="库存"
            name="stock"
            rules={[{ required: true, message: '请输入库存' }]}
          >
            <InputNumber placeholder="请输入库存" />
          </Form.Item>
          <Form.Item label="图片" valuePropName="picture1">
            <Upload
              name="picture1"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
              ) : (
                uploadButton
              )}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="编辑医疗服务"
        open={isModalOpen33}
        onCancel={() => setIsModalOpen33(false)}
        onOk={async () => {
          const params = form.getFieldsValue();
          if (params) {
            const result = await updateMedicalServices({
              ...params,
              mid:row?.mid
            });
            if (result.state === 200) {
              message.success('编辑成功');
              setIsModalOpen33(false);
              setRefreshCount(refreshCount + 1)
            }
          }
          form.submit();
        }}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          // onFinish={async(val) => {
          //   console.log(val)

          // }}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="名称"
            name="mtype"
            rules={[{ required: true, message: '请输入名称' }]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item
            label="库存"
            name="mstock"
            rules={[{ required: true, message: '请输入库存' }]}
          >
            <InputNumber placeholder="请输入库存" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="编辑医疗用品"
        open={isModalOpen44}
        onCancel={() => setIsModalOpen44(false)}
        onOk={async () => {
          const params = form.getFieldsValue();
          if (params) {
            const result = await updateDrug({
              ...params,
              drugId:row?.drugId,
            });
            if (result.state === 200) {
              message.success('编辑成功');
              setIsModalOpen44(false);
              setRefreshCount(refreshCount + 1)
            }
          }
          form.submit();
        }}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          // onFinish={async(val) => {
          //   console.log(val)

          // }}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="名称"
            name="drugType"
            rules={[{ required: true, message: '请输入名称' }]}
          >
            <Input placeholder="请输入名称" />
          </Form.Item>
          <Form.Item
            label="库存"
            name="drugStock"
            rules={[{ required: true, message: '请输入库存' }]}
          >
            <InputNumber placeholder="请输入库存" />
          </Form.Item>
        </Form>
      </Modal>
        </div>
      : 
      <Result
      status="403"
      title="非管理员账户"
      subTitle="您没有权限进入管理员页面"
      extra={<Button type="primary" onClick={() => {
        window.localStorage.removeItem('info')
        window.localStorage.removeItem('token')
        history.push('login')
      }}>返回登录</Button>}
    />
      }
      
    </div>
  );
};

export default Admin;
